package com.two.reggie.controller;

import com.two.reggie.common.PageResult;
import com.two.reggie.common.Result;
import com.two.reggie.pojo.Employee;
import com.two.reggie.service.Two_EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;

@RestController
@RequestMapping("/employee")
public class Two_EmployeeController {

    @Autowired
    private Two_EmployeeService employeeService;  // 自动注入服务层，调用业务逻辑

    @GetMapping()
    public Result list(Integer page, Integer pageSize, String name){
        PageResult pageResult = employeeService.queryEmployeeList(page, pageSize, name); // 查询员工列表
        return Result.success("查询成功", pageResult); // 返回查询结果
    }

    @PostMapping("/login")
    public Result login_xie(@RequestBody Employee emp, HttpSession session){
        Employee employee = employeeService.queryEmployeeByUserName(emp.getUsername()); // 查找员工
        if (employee == null || !employee.getPassword().equals(DigestUtils.md5DigestAsHex(emp.getPassword().getBytes()))) {
            return Result.error("用户名或密码错误"); // 密码验证失败
        }
        if (employee.getStatus() != 1) {
            return Result.error("该员工已禁用"); // 员工状态为禁用
        }
        session.setAttribute("empId", employee.getId()); // 设置 session
        return Result.success("登录成功", employee); // 登录成功返回员工信息
    }

    @PostMapping("/logout")
    public Result logout_xie(HttpSession session){
        session.removeAttribute("empId"); // 清除 session 中的登录信息
        return Result.success("退出成功"); // 返回退出成功
    }

    @PostMapping()
    public Result save(@RequestBody Employee employee, HttpSession session){
        Long empId = (Long) session.getAttribute("empId"); // 获取当前登录的管理员 ID
        // 设置默认信息
        employee.setUpdateUser(empId);
        employee.setUpdateTime(LocalDateTime.now());

        employee.setCreateUser(empId);  // 设置创建人
        employee.setCreateTime(LocalDateTime.now());  // 设置创建时间
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));  // 设置默认密码并加密
        Integer ret = employeeService.save(employee); // 保存员工信息
        return ret > 0 ? Result.success("新增成功") : Result.error("新增失败"); // 根据保存结果返回响应
    }

    @GetMapping("{id}")
    public Result getEmpById(@PathVariable Long id){
        return Result.success(employeeService.queryEmployeeById(id)); // 查询并返回员工信息
    }

    @PutMapping()
    public Result updateEmp(@RequestBody Employee employee, HttpSession session){
        Long empId = (Long) session.getAttribute("empId"); // 获取当前登录的管理员 ID
        employee.setUpdateTime(LocalDateTime.now()); // 设置更新时间
        employee.setUpdateUser(empId);  // 设置更新人
        Integer ret = employeeService.update(employee); // 更新员工信息
        return ret > 0 ? Result.success("修改成功") : Result.error("修改失败"); // 返回更新结果
    }
}
